package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 定时关闭未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?")//每三十秒执行一次
    public void cancelOrder(){
        //查询符合条件订单（待支付，十五分钟之前下单）
        LocalDateTime beforeTime=LocalDateTime.now().minusMinutes(15);//提前多长时间
        List<Orders> ordersList=ordersMapper.selectByStatusAndLtTime(1,beforeTime);//查询

        //如果有这样的订单，取消订单-修改订单状态
        if (!CollectionUtils.isEmpty(ordersList)){
            ordersList.stream().forEach(orders ->{
                log.info("执行定时取消订单的操作：{}",orders.getId());
                //取消订单
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时，订单取消");
                ordersMapper.update(orders);
                    }
                    );
        }



    }
    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", new Date());
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = ordersMapper.selectByStatusAndLtTime(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                ordersMapper.update(order);
            });
        }
    }
}
